window.onload = function () {
  // 页面加载时确保弹窗不弹出
  document.getElementById("classModal").style.display = "none";
  loadClassData(); // 页面加载时从数据源加载班级数据
};

let currentClassId = null; // 当前操作的班级ID
let classData = []; // 存储班级数据

// 加载班级数据
function loadClassData(pageNum = 1, pageSize = 10) {
  const tableBody = document.getElementById("classTableBody");
  tableBody.innerHTML = ""; // 清空表格内容

  fetch('http://localhost:8083/api/admin/class/list', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token') // 使用token进行身份验证
    },
    body: JSON.stringify({
      pageNum: pageNum, // 分页参数
      pageSize: pageSize
    })
  })
  .then(response => response.json())
  .then(data => {
    if (data.code === 200) {
      classData = data.data.records; // 假设返回数据中有 records 字段
      renderClassData(classData);
    } else {
      console.error('加载班级数据失败:', data.message);
    }
  })
  .catch(error => {
    console.error("加载班级数据失败:", error);
  });
}

// 渲染班级数据
function renderClassData(data) {
  const tableBody = document.getElementById("classTableBody");
  tableBody.innerHTML = ""; // 清空表格内容

  data.forEach(classItem => {
    const newRow = document.createElement("tr");
    newRow.id = `class-${classItem.id}`;
    newRow.innerHTML = `
      <td>${classItem.id}</td>
      <td>${classItem.name}</td>
      <td>${classItem.createdAt}</td>
      <td>${classItem.description}</td>
      <td>${classItem.teacher}</td>
      <td>
        <button onclick="deleteClass(${classItem.id})">删除</button>
        <button onclick="openModal('edit', ${classItem.id})">编辑</button>
      </td>
    `;
    tableBody.appendChild(newRow);
  });
}

// 打开弹窗
function openModal(action, classId = null) {
  const modal = document.getElementById("classModal");
  const modalTitle = document.getElementById("modal-title");
  const saveBtn = document.getElementById("save-btn");

  if (action === 'create') {
    modalTitle.textContent = "新增教学班";
    saveBtn.textContent = "保存";
    document.getElementById("className").value = ""; // 清空输入框
    document.getElementById("classDescription").value = ""; // 清空描述
    document.getElementById("teacherName").value = ""; // 清空教师名
    currentClassId = null;
  } else if (action === 'edit') {
    modalTitle.textContent = "编辑教学班";
    saveBtn.textContent = "保存修改";
    currentClassId = classId;

    fetch(`http://localhost:8083/api/admin/class/${classId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    .then(response => response.json())
    .then(data => {
      const classItem = data.data;
      document.getElementById("className").value = classItem.name;
      document.getElementById("classDescription").value = classItem.description;
      document.getElementById("teacherName").value = classItem.teacher;
    })
    .catch(error => {
      console.error("获取班级数据失败:", error);
    });
  }

  modal.style.display = "block"; // 打开弹窗
}

// 关闭弹窗
document.getElementById("cancel-btn").addEventListener("click", function() {
  const modal = document.getElementById("classModal");
  modal.style.display = "none"; // 关闭弹窗
});

// 保存班级数据
document.getElementById("class-form").addEventListener("submit", function (event) {
  event.preventDefault(); // 阻止表单默认提交行为

  const className = document.getElementById("className").value.trim();
  const classDescription = document.getElementById("classDescription").value.trim();
  const teacherName = document.getElementById("teacherName").value.trim();
  if (className === "" || teacherName === "") {
    alert("班级名称和教师是必填项");
    return;
  }

  const currentTime = new Date();
  const formattedTime = currentTime.getFullYear() + '-' +
                        ('0' + (currentTime.getMonth() + 1)).slice(-2) + '-' +
                        ('0' + currentTime.getDate()).slice(-2) + ' ' +
                        ('0' + currentTime.getHours()).slice(-2) + ':' +
                        ('0' + currentTime.getMinutes()).slice(-2) + ':' +
                        ('0' + currentTime.getSeconds()).slice(-2); // 格式化为 YYYY-MM-DD HH:mm:ss

  const classDTO = {
    name: className,
    description: classDescription,
    teacher: teacherName,
    createdAt: formattedTime // 保持创建时间
  };

  if (currentClassId === null) {
    // 新增班级
    fetch('http://localhost:8083/api/admin/class/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify(classDTO)
    })
    .then(response => response.json())
    .then(data => {
      loadClassData(); // 重新加载班级数据
      document.getElementById("classModal").style.display = "none"; // 关闭弹窗
    })
    .catch(error => {
      console.error("新增班级失败:", error);
    });
  } else {
    // 编辑班级
    classDTO.id = currentClassId; // 编辑时需要传递班级ID

    fetch('http://localhost:8083/api/admin/class/update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify(classDTO)
    })
    .then(response => response.json())
    .then(data => {
      loadClassData(); // 重新加载班级数据
      document.getElementById("classModal").style.display = "none"; // 关闭弹窗
    })
    .catch(error => {
      console.error("编辑班级失败:", error);
    });
  }
});

// 删除班级
function deleteClass(classId) {
  fetch(`http://localhost:8083/api/admin/class/delete/${classId}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  })
  .then(response => response.json())
  .then(data => {
    loadClassData(); // 重新加载班级数据
  })
  .catch(error => {
    console.error("删除班级失败:", error);
  });
}

// 搜索功能
document.getElementById("searchBtn").addEventListener("click", function() {
  const searchTerm = document.getElementById("searchInput").value.toLowerCase();
  const filteredData = classData.filter(classItem => {
    return classItem.name.toLowerCase().includes(searchTerm) ||
           classItem.description.toLowerCase().includes(searchTerm) ||
           classItem.teacher.toLowerCase().includes(searchTerm);
  });

  renderClassData(filteredData); // 渲染过滤后的数据
});

// 退出按钮点击事件
document.getElementById("logout-btn").addEventListener("click", () => {
  window.location.href = '../login.html'; // 跳转到登录页面
});
